package bhwz.seac3.ui.user;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

import bhwz.seac3.LocalBLServiceManager;
import bhwz.seac3.RMIClientBLServiceManager;
import bhwz.seac3.blservice.AutoRedisplay;
import bhwz.seac3.blservice.query.MatchQueryBLService;
import bhwz.seac3.blservice.query.TeamQueryBLService;
import bhwz.seac3.ui.user.graphics.Graphics;
import bhwz.seac3.util.SVGManager;
import bhwz.seac3.util.SortableTable;
import bhwz.seac3.util.SortableTableModel;
import bhwz.seac3.vo.MatchVo;
import bhwz.seac3.vo.TeamVo;

import javax.swing.JScrollPane;
import javax.swing.table.TableModel;

import org.apache.batik.swing.JSVGCanvas;
import org.w3c.dom.svg.SVGDocument;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class TeamDetailDialog extends JDialog implements AutoRedisplay {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String season;
	private JPanel contentPane;
	private JPanel contentPane0;
	private SortableTable table;
	private Object[][] info;
	private final Object[] columns = { "比赛时间", "比赛队伍", "比分" };
	private final int width = 1400, height = 700;
	private TeamVo vo;
	private JScrollPane scrollPaneSouth;
	private JScrollPane scrollPane;

	public TeamDetailDialog(Frame owner, TeamVo vo,String season) {
		
		super(owner);
		
		this.setTitle("Team : "+vo.get球队全名()+"\tSeason : "+season);
		this.setResizable(false);
		this.season=season;
		this.vo = vo;
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

		setVisible(true);
		setBounds(150, 0, width, height);
		contentPane = new JPanel();
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		contentPane.setBackground(Color.white);

		JPanel panelWest = new JPanel();
		panelWest.setSize(300, 500);
		panelWest.setBackground(Color.white);
		GridBagLayout gbl_panelWest = new GridBagLayout();
		gbl_panelWest.columnWidths = new int[] { 57, 184, 1, 0 };
		gbl_panelWest.rowHeights = new int[] { 214, 0, 0 };
		gbl_panelWest.columnWeights = new double[] { 1.0, 0.0, 0.0,
				Double.MIN_VALUE };
		gbl_panelWest.rowWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
		panelWest.setLayout(gbl_panelWest);

		JPanel p = new JPanel();
		GridBagConstraints gbc_p = new GridBagConstraints();
		gbc_p.gridwidth = 2;
		gbc_p.insets = new Insets(5, 5, 5, 5);
		gbc_p.gridx = 0;
		gbc_p.gridy = 0;
		panelWest.add(p, gbc_p);

		JSVGCanvas canvas = new JSVGCanvas();
		p.add(canvas);
		SVGDocument svgd;

		try {
			svgd = new SVGManager().decodeImage(vo.getTeamIcon());
			canvas.setSVGDocument(svgd);
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}

		contentPane.add(panelWest, BorderLayout.WEST);

		JPanel panelWestSouth = new JPanel();
		panelWestSouth.setBackground(Color.white);
		panelWestSouth.setLayout(null);
		GridBagConstraints gbc_panelWestSouth = new GridBagConstraints();
		gbc_panelWestSouth.gridwidth = 2;
		gbc_panelWestSouth.insets = new Insets(0, 0, 0, 5);
		gbc_panelWestSouth.fill = GridBagConstraints.BOTH;
		gbc_panelWestSouth.gridx = 0;
		gbc_panelWestSouth.gridy = 1;
		panelWest.add(panelWestSouth, gbc_panelWestSouth);

		String[] teamInfo = { "球队简称", "球队全名", "所在地", "赛区", "分区", "主场", "建立时间" };
		String[] teamInfoGet = { vo.get球队简称(), vo.get球队全名(), vo.get所在地(),
				vo.get赛区(), vo.get分区(), vo.get主场(), vo.get建立时间() };
		int gap1 = 27, y1 = -10;
		for (int i = 0; i < teamInfo.length; i++) {
			JLabel l = new JLabel(teamInfo[i] + ":" + teamInfoGet[i]);
			l.setBounds(30, y1 += gap1, 200, 15);
			panelWestSouth.add(l);
		}
		
		scrollPane = new JScrollPane();
		scrollPane
				.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane
				.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
		contentPane.add(scrollPane, BorderLayout.CENTER);
		displayTeamData();
		displayMatches();
		
		
		this.setVisible(true);

		LocalBLServiceManager.getRedisplayControllerBLService().register(this);
	}

	private void displayTeamData() {
		
		contentPane0 = new JPanel();
		contentPane0.setPreferredSize(new Dimension(500, height));
		contentPane0.setLayout(new BorderLayout(0, 0));
		JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.TOP);
		contentPane0.add(tabbedPane, BorderLayout.CENTER);
		
		JPanel panel = new JPanel();
		tabbedPane.addTab("    详细数据     ", null, panel, null);
		panel.setLayout(null);
		
		//panel.setPreferredSize(new Dimension(500, height));
		panel.setBackground(Color.white);
		panel.setLayout(null);
		String basicData[] = { "基础数据", "比赛场数", "战绩", "胜率", "得分", "对手得分", "篮板",
				"前场篮板", "后场篮板", "助攻", "抢断", "三分出手数","三分命中数", "盖帽", "失误", "犯规" };
		String grades = vo.get胜利场数() + "" + "-" + (vo.get比赛场数() - vo.get胜利场数())
				+ "";
		Object[] itemsGetBasic = { "", vo.get比赛场数(), grades, vo.get胜率(),
				vo.get比赛得分(), vo.get对手得分(), vo.get篮板数(), vo.get前场篮板数(),
				vo.get后场篮板数(), vo.get助攻数(), vo.get断球数(),vo.get三分出手数(),vo.get三分命中数(),
				vo.get盖帽数(), vo.get失误数(), vo.get犯规数() };
		int gap = 30, y = 0;
		for (int i = 0; i < itemsGetBasic.length; i++) {
			JLabel l = new JLabel(basicData[i] + ":"
					+ formatDouble(itemsGetBasic[i]));
			l.setBounds(50, y += gap, 200, 50);
			panel.add(l);
		}

		String highLevelData[] = { "高级数据", "进攻回合", "防守回合", "进攻效率", "防守效率",
				"对手进攻篮板数", "对手防守篮板数", "进攻篮板效率", "防守篮板效率", "命中率", "三分命中率", "罚球",
				"罚球命中率", "助攻效率", "抢断率" };
		String freeThrow = (int) vo.get罚球命中数() + "" + "-" + (int) vo.get罚球数()
				+ "";
		Object[] itemsGetHigh = { "", vo.get进攻回合(), vo.get防守回合(), vo.get进攻效率(),
				vo.get防守效率(), vo.get对手进攻篮板数(), vo.get对方防守篮板数(), vo.get进攻篮板效率(),
				vo.get防守篮板效率(), vo.get命中率(), vo.get三分命中率(), freeThrow,
				vo.get罚球命中率(), vo.get助攻率(), vo.get抢断效率() };
		y = 0;
		for (int i = 0; i < itemsGetHigh.length; i++) {
			JLabel l = new JLabel(highLevelData[i] + ":"
					+ formatDouble(itemsGetHigh[i]));
			l.setBounds(270, y += gap, 200, 50);
			panel.add(l);
		}		
		
		JPanel imagePanel = new JPanel();
		imagePanel.setBackground(Color.white);
		tabbedPane.addTab("    图表展现     ", null, imagePanel, null);
		imagePanel.setLayout(new BoxLayout(imagePanel, BoxLayout.Y_AXIS));
		
		JPanel chartPanel =getRadarChart();
		imagePanel.add(chartPanel);
	
		
		JPanel chartPanel2 =getLineChart();
		imagePanel.add(chartPanel2);
		scrollPane.setViewportView(contentPane0);
	}

	private Object[][] matchToArray(List<MatchVo> matches) {
		int length = matches.size();
		Object[][] info = new Object[length][4];
		for (int n = 0; n < length; n++) {
			MatchVo match = matches.get(n);
			info[n][0] = new SimpleDateFormat("yyyy-MM-dd").format(new Date(
					match.getDate()));
			info[n][1] = match.getTeam1() + "-" + match.getTeam2();
			info[n][2] = match.getTeam1Score() + ":" + match.getTeam2Score();
		}
		return info;

	}

	private Object formatDouble(Object i) {
		if (i instanceof Double) {
			DecimalFormat df = new DecimalFormat("#.###");
			return df.format(i);
		}
		return i;
	}

	@Override
	public void redisplay() {
		try {
			vo=((TeamQueryBLService)RMIClientBLServiceManager.getBLService(TeamQueryBLService.class)).query场均数据ByName(vo.get球队简称(), season);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		displayMatches();
		displayTeamData();
	}

	private void displayMatches() {
		try {
			List<MatchVo> matches = ((MatchQueryBLService) RMIClientBLServiceManager
					.getBLService(MatchQueryBLService.class)).queryByTeam(
					vo.get球队简称(), vo.get赛季());
			
			matches.sort((m1,m2)->(int)(m2.getDate()-m1.getDate()));

			info = matchToArray(matches);

			TableModel model = new SortableTableModel(info, columns);
			table = new SortableTable(model);
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			table.addDoubleClickOnDataListener(
					DetailsListenerFactory.getMatchDetailListener(season), 0, 1);
		} catch (Exception e1) {
			JOptionPane
					.showMessageDialog(this, "服务器连接发生异常\n" + e1.getMessage());
			e1.printStackTrace();
		}
		table.getColumnModel().getColumn(0).setPreferredWidth(130);
		table.getColumnModel().getColumn(1).setPreferredWidth(130);
		table.getColumnModel().getColumn(2).setPreferredWidth(140);
		if (scrollPaneSouth == null) {
			scrollPaneSouth = new JScrollPane(table);
			scrollPaneSouth.setPreferredSize(new Dimension(410, 100));
			scrollPaneSouth
					.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
			contentPane.add(scrollPaneSouth, BorderLayout.EAST);
		} else
			scrollPaneSouth.setViewportView(table);

	}
	
	private JPanel getRadarChart(){
		try {
			TeamQueryBLService tbl=RMIClientBLServiceManager.getBLService(TeamQueryBLService.class);
			vo=tbl.query场均数据ByName(vo.get球队简称(), season);
		
		List<String> valueNames=Arrays.asList(new String[]{"胜率","进攻效率","防守效率","抢断效率","助攻效率"});
		List<Double> maxValues=Arrays.asList(new Double[]{
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get胜率()).get(3).get胜率(),
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get进攻效率()).get(3).get进攻效率(),
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get防守效率()).get(3).get防守效率(),
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get抢断效率()).get(3).get抢断效率(),
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get助攻率()).get(3).get助攻率(),
		});
		List<Double> values=Arrays.asList(new Double[]{
				vo.get胜率()/maxValues.get(0),vo.get进攻效率()/maxValues.get(1),vo.get防守效率()/maxValues.get(2),vo.get抢断效率()/maxValues.get(3),vo.get助攻率()/maxValues.get(4)
		});
		List<Double> medianValues=Arrays.asList(new Double[]{
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get胜率()).get(1).get胜率()/maxValues.get(0),
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get进攻效率()).get(1).get进攻效率()/maxValues.get(1),
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get防守效率()).get(1).get防守效率()/maxValues.get(2),
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get抢断效率()).get(1).get抢断效率()/maxValues.get(3),
				tbl.query所有球队赛季表现四分位数(season, vo->vo.get助攻率()).get(1).get助攻率()/maxValues.get(4),
		});
		
		return Graphics.getRadarChart("球队能力", valueNames, values, medianValues);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private JPanel getLineChart(){
		return new TeamProgressPanel(vo);
	}

}
